import 'package:flutter/material.dart';
import '../tokens/design_spec.dart';
import '../tokens/font_sizes.dart';

class Responsive {
  static double w(double value,
      {BuildContext? context, double? min, double? max}) {
    final Size size = _getSize(context);
    final double scaleFactor = size.width / DesignSpec.baseWidth;
    double result = value * scaleFactor;
    if (min != null) result = result.clamp(min, double.infinity);
    if (max != null) result = result.clamp(0, max);
    return result;
  }

  static double h(double value,
      {BuildContext? context, double? min, double? max}) {
    final Size size = _getSize(context);
    final double scaleFactor = size.height / DesignSpec.baseHeight;
    double result = value * scaleFactor;
    if (min != null) result = result.clamp(min, double.infinity);
    if (max != null) result = result.clamp(0, max);
    return result;
  }

  static double sp(TextSizeToken token, {BuildContext? context}) {
    if (!token.scalable) return token.size;

    final Size size = _getSize(context);
    final double scaleFactor = size.shortestSide / DesignSpec.baseShortSide;
    double result = token.size * scaleFactor;

    if (token.max != null) result = result.clamp(0, token.max!);
    if (token.min != null) result = result.clamp(token.min!, double.infinity);

    return result;
  }

  static Size _getSize(BuildContext? context) {
    if (context != null) return MediaQuery.of(context).size;

    final window = WidgetsBinding.instance.platformDispatcher.views.first;
    final pixelRatio = window.devicePixelRatio;
    final physicalSize = window.physicalSize;
    return physicalSize / pixelRatio;
  }
}
